<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace model;

use api\portal\model\MerchModel;
use cmf\lib\taglib\Cmf;
use think\Model;

class OrderModel extends Model
{

    /**
     * 模型名称
     * @var string
     */
    protected $name = 'order';

    protected $type = [
        'more' => 'array',
    ];

    /**
     * 整理数据
     * @param $row
     * @return mixed
     */
    public function decode(&$row)
    {

        //状态
        switch ($row['status']) {
            case 0 :
                $row['status_name'] = '待支付';
                continue;
            case 1 :
                $row['status_name'] = '待使用';
                continue;
            case 2 :
                $row['status_name'] = '已使用';
                continue;
        }


        if (isset($row['thumb'])) {
            $row['thumb'] = cmf_get_asset_url($row['thumb']);
        }

        $merchName = MerchModel::where(['id' => $row['merch_id']])->field('name')->find();
        $row['merch_name'] = $merchName['name'];

//        $row['receive_url'] = '';
//         if ($row['status'] == 2){
//             $row['receive_url'] = cmf_get_domain() .'/api/portal/merch/orderReceive?orderno='.$row['order_no'];
//         }

        return $row;
    }

    /**
     * @param string $pre
     * @throws \Exception
     */
    public static function getOrderNo($pre = 'OR')
    {
        $order = $pre . time() . random_int(1000, 9999);
        $count = self::where(['order_no' => $order])->count();
        if ($count) {
            self::getOrderNo();
        }
        return $order;
    }

    /**
     * @param string $pre
     * @throws \Exception
     */
    public static function getReceiveCode()
    {
        $code = self::GetRandStr(8);

        $count = self::where(['receive_code' => $code])->count();
        if ($count) {
            self::getOrderNo();
        }
        return $code;
    }

    private static function GetRandStr($length)
    {
        //字符组合
        $str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $len = strlen($str) - 1;
        $randstr = '';
        for ($i = 0; $i < $length; $i++) {
            $num = mt_rand(0, $len);
            $randstr .= $str[$num];
        }
        return $randstr;
    }

}